package com.fast.user.web.controller.member;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.fast.base.db.page.PageView;
import com.fast.base.db.sql.impl.SqlGeneratorImpl;
import com.fast.base.model.AnoSysLog;
import com.fast.base.security.StringEncrypt;
import com.fast.base.util.ChineseSpelling;
import com.fast.base.util.DateUtils;
import com.fast.base.util.LogUtils;
import com.fast.base.util.PropertiesUtils;
import com.fast.base.util.StringUtils;
import com.fast.base.util.data.MathUtils;
import com.fast.base.util.file.CompressPic;
import com.fast.base.util.web.ResponseData;
import com.fast.base.util.web.ResponseEnum;
import com.fast.base.web.BaseController;
import com.fast.common.userCache.MemberCacheUtils;
import com.fast.common.userCache.UserRequestUtils;
import com.fast.user.model.admin.AdminUser;
import com.fast.user.model.admin.Group;
import com.fast.user.model.member.Member;
import com.fast.user.service.admin.AdminUserService;
import com.fast.user.service.member.MemberService;
import com.fast.user.web.form.web.MemberListForm;

/**
 * ClassName:MemberController <br/>
 * 用途:Member信息控制处理 <br/>
 * 开发人员：lushuifa http://lushuifa.iteye.com/ 邮箱:lsflu@126.com
 * 
 * @version
 * @since JDK 1.6
 * @see Date: 2016年11月30日 14时51分41秒 <br/>
 */
@Controller
@RequestMapping("/member")
public class MemberController extends BaseController{
	
	@Resource(name="memberService")
	private MemberService memberService;
	
	@Resource(name="adminUserService")
	private AdminUserService adminUserService;
	
	
	/**
	 * 说明: 导入会员数据 <br>
	 * 编写者:lushuifa
	 * 创建时间:2018年8月18日 下午3:57:53 </pre>
	 * @param 
	 * @return ResponseData 说明
	 */
	@ResponseBody
	@RequestMapping("/importDataFromXls.do")
	public ResponseData importDataFromXls(@RequestParam MultipartFile impFile){
		ResponseData responseData = new ResponseData();
		//再导入详情信息
		String strDirPath = super.getRequest().getSession().getServletContext().getRealPath("/");
		String savePath = strDirPath + "/excel/";
		String fileDiskPath = "";
		try {
			if (!impFile.isEmpty()) {
				String fileName = "memberList.xls";
				fileDiskPath = savePath + fileName;
				impFile.transferTo(new File(fileDiskPath));
			}
			boolean impFlag = this.memberService.batchSaveMemberByImpFile(fileDiskPath);
			if (impFlag) {
				responseData.success();
			} else {
				responseData.failue();
				responseData.setMsg("导入失败请检查一下你的内容！");
			}
		} catch (IOException e1) {
			responseData.failue();
			LogUtils.error("importDataFromXls error:", e1);
		}
		return responseData;
	}
	
	/**
	 * 说明:恢复删除数据 <br>
	 * 编写者:lushuifa
	 * 创建时间:2018年8月18日 下午9:19:34 </pre>
	 * @param 
	 * @return ResponseData 说明
	 */
	@ResponseBody
	@RequestMapping("/batchRebackData.do")
	@AnoSysLog(actionName="批量恢复已删除的数据")
	public ResponseData batchRebackData(String ids){
		ResponseData responseData = new ResponseData();
		try {
			boolean actionFlag = memberService.batchRebackDeleteData(Member.class, ids);
			responseData.setCode(actionFlag?"00":"01");
			if(actionFlag){
				responseData.setMsg("你选中的数据恢复数据成功");
			}else{
				responseData.setMsg("你选中的数据恢复数据失败,请与管理员联系！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 用户登录
	 * @param session
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/webLogin.out")
	@AnoSysLog(actionName="前台登录系统")
	public ResponseData webLogin(String loginName,String password){
		ResponseData j = new ResponseData();
		try {
			//判断是否是后台审批用户
			boolean isExistAdmin = adminUserService.isExistUser(loginName);
			if(isExistAdmin){
				AdminUser adminUser = adminUserService.login(loginName,StringEncrypt.SHA256(password));
				if (adminUser != null) {
					if(adminUser.getGroupName().equals("文件审批人员")){
						this.adminUserService.updateLoginInfo(adminUser);
						adminUser.setLoginCount(adminUser.getLoginCount()+1);
						j.setData(adminUser);
						webUtil.setSessionAttr("adminUser", adminUser);
						Group group = this.adminUserService.getById(Group.class,adminUser.getGroupId());
						webUtil.setSessionAttr("group", group);
						j.setCode("99");
						return j;
					}
				}
			}
			//核实用户名在数据中是否存在
			boolean isExist = memberService.isExistUser(loginName);
			if(isExist){
				Member member = memberService.login(loginName,password);
				if (member != null) {
					if(member.getLocked()==0){
						member.setLoginIp(webUtil.getIpAddr());
						member.setLoginDateTime(DateUtils.getNow());
						member.setLoginCount(member.getLoginCount()+1);
						String updateSql = "update "+SqlGeneratorImpl.getTableName(Member.class)+" set loginIp='"+webUtil.getIpAddr()+"',loginDateTime='"+DateUtils.getNow()+"',loginCount=loginCount+1 where id="+member.getId();
						this.memberService.modifyRow(updateSql);
						//改变登录次数
						int newCount = this.memberService.increaseLoginCount(member.getId());
						member.setLoginCount(newCount);
						if(!member.getHeadImageUrl().equals("")){
							member.setHeadImageUrl(getImgPath()+member.getHeadImageUrl());
						}
						j.setData(member);
						webUtil.setSessionAttr("member",member);
						String cookieV = URLEncoder.encode(JSONObject.toJSONString(member), "UTF-8");
						Cookie cookie = new Cookie("curMember",cookieV);
						cookie.setPath("/front");
						cookie.setMaxAge(60*60*24);
						webUtil.getResponse().addCookie(cookie);
					} else {
						j.setCode("01");
						j.setMsg("此用户被锁住了,请确认是否验证邮箱！");
					}
				}else{
					j.setCode("01");
					j.setMsg("密码错误,请重新输入！");
				}
			}else{
				j.setCode("01");
				j.setMsg("系统不存在该用户！");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			j.setMsg("系统异常,请尝试重新操作！");
		}
		return j;
	}
	
	
	/**

	 * 用户退出登录

	 * @return

	 */
	@RequestMapping("/loginOut.out")
	@AnoSysLog(actionName="后台退出系统")
	public String loginOut(String actionType){
		ResponseData j = new ResponseData();
		try {
			Member member = (Member) webUtil.getSessionAttr("member");
			if(member!=null){
				webUtil.removeSessionAttr("member");
				Cookie cookie = new Cookie("curMember", null); 
				cookie.setMaxAge(0);
				cookie.setPath("/front");
				webUtil.getResponse().addCookie(cookie); 
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		j.setCode("00");
		if(actionType.equals("declareFile")){
			return "redirect:/front/memberCenter.jsp";
		}else{
			return "redirect:/front/index.jsp";
		}
		
	}
	
	/**
	 * 标题：checkIdcard <br/>
	 * 作用：检查身份证号是否存在<br/>
	 * @author developer-lushuifa
	 * @param  loginName
	 * @throws Exception
	 * @since  JDK 1.6
	 */
	@ResponseBody
	@RequestMapping(value="/checkIdcard.do")
	public String checkIdcard(String idcard) throws Exception {
		boolean isExist = this.memberService.isExistIdCard(idcard);
		return Boolean.toString(!isExist);
	}
	
	/**
	 * 核对当前的密码是否正确
	 * @param password
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/checkPassword.do")
	public String checkPassword(String password) throws Exception {
		String uuid = MemberCacheUtils.getLoginMember().getUuid();
		password = StringEncrypt.SHA256(password);
		boolean isExist = this.memberService.checkPassword(uuid,password);
		return Boolean.toString(isExist);
	}
	
	/**
	 * 标题：checkMobile <br/>
	 * 作用：检查手机号是否存在<br/>
	 * @author developer-lushuifa
	 * @param  loginName
	 * @throws Exception
	 * @since JDK 1.6
	 */
	@ResponseBody
	@RequestMapping(value="/checkMobile.do")
	public String checkMobile(HttpServletResponse response, String mobile) throws Exception {
		boolean isExist = this.memberService.isExistMobile(mobile);
		Member member = MemberCacheUtils.getLoginMember();
		if(member!=null){
			if(mobile.equals(member.getMobile())){
				isExist = this.memberService.isExistMobile(mobile,member.getId());
			}
		}
		return String.valueOf(!isExist);
	}
	
	
	/**
	 * 标题：checkEmail <br/>
	 * 作用：  检查邮箱是否存在  <br/>
	 * @author developer-lushuifa
	 * @param loginName
	 * @throws Exception
	 * @since JDK 1.6
	 */
	@ResponseBody
	@RequestMapping(value="/checkEmail.do")
	public String checkEmail(HttpServletResponse response, String email) throws Exception {
		boolean isExist = this.memberService.isExistEmail(email);
		Member member = MemberCacheUtils.getLoginMember();
		if(member!=null){
			if(email.equals(member.getEmail())){
				isExist = this.memberService.isExistEmail(email,member.getId());
			}
		}
		return String.valueOf(!isExist);
	}
	
	/**
	 * 标题：checkLoginName <br/>
	 * 作用：  检查用户名是否存在  <br/>
	 * @author developer-lushuifa
	 * @param loginName
	 * @throws Exception
	 * @since JDK 1.6
	 */
	@ResponseBody
	@RequestMapping(value="/checkLoginName.do")
	public String checkLoginName(HttpServletResponse response, String loginName) throws Exception {
		boolean isExist = this.memberService.isExistLoginName(loginName);
		Member member = MemberCacheUtils.getLoginMember();
		if(member!=null){
			if(loginName.equals(member.getNickName())){
				int memberId = member.getId();
				isExist = this.memberService.isExistLoginName(loginName,memberId);
			}
		}
		return String.valueOf(!isExist);
	}
	
	/**
	 * 编辑[Member]的头像信息
	 * @param Member
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/editMemberHeadPicInfo.do")
	public ResponseData editMemberHeadPicInfo(@RequestParam MultipartFile headpic) {
		Member member = null;
		ResponseData responseData = new ResponseData();
		/**
		 * 上传文件
		 */
		String headpicPath = "";
		responseData.setCode("00");
		try {
			if(!headpic.isEmpty()){
				String fileName = MathUtils.getTheOnlyStr()+ChineseSpelling.getSpell(headpic.getOriginalFilename());
				String savePath = PropertiesUtils.getCoreContextProperty("fileDisk")+"headpic/";
				headpicPath  = "headpic/"+fileName;
				//判断文件大小
				System.out.println(headpic.getSize());
				if(headpic.getSize()>1024*1024){
					responseData.setMsg("图片不能大于1M");
					responseData.setCode("01");
				}
				FileUtils.copyInputStreamToFile(headpic.getInputStream(), new File(savePath,fileName));
				//上传成功，压缩图片
				CompressPic mypic = new CompressPic();
				mypic.compressPic(savePath,savePath,fileName,fileName,800,800,true);
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		try {
			int id = webUtil.getInt("id");
			if(id>0){
				member = this.memberService.getMemberById(id);
				member = (Member) webUtil.bindDataToBean(member);
				if(!headpicPath.equals("")){
					member.setNickName(headpicPath);
				}
			}
			UserRequestUtils.bindEditorInfo(member);
			if(this.memberService.merge(member)!=null){
				responseData.setMsg("编辑编号为["+member.getUuid()+"]的头像操作成功");
				responseData.setData(member);
			}
			responseData.setCode("00");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setMsg("编辑编号为["+member.getUuid()+"]的头像信息操作失败");
		}
		return responseData;
	}
	
	/**
	 * 删除[Member]信息到回收站
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delMember2hs.do")
	public ResponseData delMember2hs(int id) {
		ResponseData responseData = new ResponseData();
		try {
			boolean actionFlag = this.memberService.deleteByIdForHS(Member.class, id);
			responseData.setCode(actionFlag?"00":"01");
			if(actionFlag){
				responseData.buildResult(ResponseEnum.DELETE_SUCCESS);;
			}else{
				responseData.buildResult(ResponseEnum.DELETE_FAILUE);;
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 删除多个[Member]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/batchDelMemberForHS.do")
	public ResponseData batchDelMemberForHS(String ids) {
		ResponseData responseData = new ResponseData();
		try {
			boolean actionFlag = this.memberService.batchDeleteByIdsForHS(Member.class,ids);
			if(actionFlag){
				responseData.buildResult(ResponseEnum.DELETE_SUCCESS);;
			}else{
				responseData.buildResult(ResponseEnum.DELETE_FAILUE);;
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 得到[Member]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getJsonDetail.do")
	public ResponseData getJsonDetail(int id) {
		ResponseData responseData = new ResponseData();
		Member bean = memberService.queryForBeanById(Member.class, id);
		try {
			responseData.setData(bean);
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 得到全部[Member]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getJsonAllList.do")
	public ResponseData getMemberAllList() {
		ResponseData responseData = new ResponseData();
		List<Member> beanList = memberService.queryForBeanList(Member.class," order by id desc");
		try {
			responseData.setData(beanList);
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	
	/**
	 * 删除[Member]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delMemberById.do")
	public ResponseData delMemberById(int id) {
		ResponseData responseData = new ResponseData();
		try {
			//先删除头像图片
			Member member = this.memberService.queryForBean(Member.class, " where id="+id+"");
			if(!member.getHeadImageUrl().equals("")&&member.getHeadImageUrl()!=null){
				String filePath = PropertiesUtils.getCoreContextProperty("fileDisk")+""+member.getHeadImageUrl();
				File file = new File(filePath);
				if(file.exists()){
					FileUtils.forceDelete(file);
				}
			}
			boolean actionFlag = memberService.deleteById(Member.class, id);
			responseData.setCode(actionFlag?"00":"01");
			if(actionFlag){
				responseData.buildResult(ResponseEnum.DELETE_SUCCESS);
			}else{
				responseData.buildResult(ResponseEnum.DELETE_FAILUE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 删除多个[Member]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/batchDelMember.do")
	public ResponseData batchDelMember(String ids) {
		ResponseData responseData = new ResponseData();
		try {
			int actionCount = memberService.deleteByIds(Member.class, ids);
			responseData.buildResult(ResponseEnum.DELETE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			responseData.buildResult(ResponseEnum.DELETE_FAILUE);
		}
		return responseData;
	}
	
	/**
	 * 修改密码
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updatePassword.do")
	public ResponseData updatePassword(int id,String newPassword){
		ResponseData responseData = new ResponseData();
		try {
			responseData = this.memberService.updatePassword(id,newPassword);
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		LogUtils.info("updatePassword result:"+responseData.toString());
		return responseData;
	}
	
	//=======================列表操作增删改查==============================
	/**
	 * 编辑[Member]信息
	 * @param Member
	 * @return
	 */
	@ResponseBody
	@RequestMapping(path={"/editMember.do"})
	public ResponseData editMember(String actionType,@RequestParam MultipartFile headImageUrl) {
		Member member = null;
		ResponseData responseData = new ResponseData();
		try {
			String uuid = webUtil.getString("uuid");
			if(StringUtils.isEmpty(uuid)){
				uuid = MathUtils.getTheOnlyStr();
			}
			String headpicPath = "";
			if(!headImageUrl.isEmpty()&&headImageUrl.getSize()>0){
				try {
					String fileDir = "member/";
					String savePath  = super.getFileDiskPath()+fileDir;
					String fileName  = uuid+ChineseSpelling.getSpell(headImageUrl.getOriginalFilename());
					headpicPath = fileDir+fileName;
					File saveFile = new File(savePath,fileName);
				    FileUtils.copyInputStreamToFile(headImageUrl.getInputStream(), saveFile);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			int id = webUtil.getInt("id");
			String loginPsd = webUtil.getString("loginPsd");
			String loginPsd2 = webUtil.getString("loginPsd2");
			
			if(!StringUtils.equals(loginPsd, loginPsd2)){
				responseData.setCode("01");
				responseData.setMsg("两次输入的密码不一致！");
				return responseData;
			}
			
			if(id>0){
				member = this.memberService.queryForBeanById(Member.class,id);
				member = (Member) webUtil.bindDataToBean(member);
				if(StringUtils.isNotEmpty(loginPsd)){
					member.setPassword(StringEncrypt.SHA256(loginPsd));
				}
				
				if(!headImageUrl.isEmpty()){
					member.setHeadImageUrl(headpicPath);
				}
			}else{
				member = new Member();
				member = (Member) webUtil.bindDataToBean(member);
				member.setUuid(MathUtils.getTheOnlyStr());
				member.setMemberGrade(1);
				member.setStatus(1);
				member.setHeadImageUrl(headpicPath);
				member.setPassword(StringEncrypt.SHA256(loginPsd));
			}
			if(this.memberService.merge(member)!=null){
				responseData.setMsg("编辑编号为["+member.getUuid()+"]操作成功");
				responseData.setData(member);
			}
			responseData.setCode("00");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setCode("01");
			responseData.setMsg("编辑编号为["+member.getUuid()+"]操作失败");
		}
		return responseData;
	}
	
	/**
	 * 用户注册
	 * @param Member
	 * @return
	 */
	@RequestMapping(path={"/regist.out"})
	public ModelAndView regist(String actionType) {
		Member member = null;
		ModelAndView modelAndView = new ModelAndView();
		try {
			int id = webUtil.getInt("id");
			if(id>0){
				member = this.memberService.queryForBeanById(Member.class,id);
				String loginPsd = webUtil.getString("loginPsd");
				String oldPsd = member.getPassword();
				member = (Member) webUtil.bindDataToBean(member);
				if(StringUtils.isEmpty(loginPsd)){
					member.setPassword(oldPsd);
				}
			}else{
				member = new Member();
				member = (Member) webUtil.bindDataToBean(member);
				member.setUuid(MathUtils.getTheOnlyStr());
				member.setMemberGrade(1);
				member.setStatus(1);
				if(actionType.equals("webReist")){
					member.setPassword(StringEncrypt.SHA256(member.getPassword()));
				}else{
					UserRequestUtils.bindCreaterInfo(member);
					member.setPassword(StringEncrypt.SHA256("data88"));
				}
			}
			if(!actionType.equals("webReist")){
				UserRequestUtils.bindEditorInfo(member);
			}
			if(this.memberService.merge(member)!=null){
				modelAndView.addObject("member", member);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelAndView.setViewName("/front/memberCenter.jsp");
		return modelAndView;
	}
	
	
	
	/**
	 * 查询详情
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getMemberDetail.do")
	public ModelAndView getMemberDetail(int id,String actionType) {
		ModelAndView mv = new ModelAndView();
		Member bean = memberService.queryForBeanById(Member.class, id);
		try {
			mv.addObject("member", bean);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(StringUtils.equals(actionType,"update")){
			mv.setViewName("/adminMain/member/member-add.jsp");
		}else{
			mv.setViewName("/adminMain/member/member-detail.jsp");
		}
		return mv;
	}
	
	/**
	 * 得到[Member]列表
	 * @throws IOException 
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/getMemberList.do", method=RequestMethod.POST)
	public Object getMemberList(MemberListForm memberListForm){
		Map<String,Object> gridMap = new HashMap<String,Object>();
		PageView<Member> pageView = new PageView<Member>();
		try {
			pageView = this.memberService.getMemberListByPage(memberListForm);
			gridMap.put("total", pageView.getTotalRecord());
			gridMap.put("rows", pageView.getRecords());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return gridMap;
	}
}
